package thread.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author yuisama
 * @date 2022/07/13 11:32
 **/
public class LockTest {
    public static void main(String[] args) {
        // 传入ture，此时就是一个公平锁
        ReentrantLock lock = new ReentrantLock(true);
        Thread t1 = new Thread(() -> {
            lock.lock(); // 代码从这里开始加锁，直到碰到unlock解锁
            // 互斥代码块
            try {
                System.out.println(Thread.currentThread().getName() + "获取到锁，其他线程等待");
                Thread.sleep(8000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock(); // 代码从这里解锁，
            }
            System.out.println(Thread.currentThread().getName() + "释放锁");
        },"春鹏");
        t1.start();
        Thread t2 = new Thread(() -> {
            boolean isLocked = false;
            try {
                isLocked = lock.tryLock(3000, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
               if (isLocked) {
                   // 只有获取锁成功的线程才需要执行unlock方法
                   lock.unlock();
               }
            }
            System.out.println("不爱我就拉倒，我去找云鹏~");
        },"水子哥");
        t2.start();
    }
}